//
//  ViewController.m
//  testWebView
//
//  Created by Li Xiaofan on 2018/8/23.
//  Copyright © 2018 Li Xiaofan. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>

static NSHTTPCookie *s_cookie;

@interface ViewController () <WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSURLRequest *request;
@property (nonatomic, strong) UILabel *label;
@end

@implementation ViewController

- (void)viewDidLoad 
{
    [super viewDidLoad];
    
    [self reCreateWebView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:UIApplicationDidBecomeActiveNotification object:NULL];
}

- (void)reCreateWebView 
{
    if (_webView) {
        [_webView removeFromSuperview];
        _webView = nil;
    }
    if (_request) {
        _request = nil;
    }
    [self initializeWebView];
    [self initializeButtons];
    
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    
//    NSHTTPCookieStorage *cookieJar2 = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    [cookieJar2 setCookie:s_cookie];
    
    [self reCreateWebViewWithScript];
    _label.text = @"新建(普通)成功!";
    _label.text = @"";
}

- (void)reCreateWebViewWithScript {
    if (_webView) {
        [_webView removeFromSuperview];
        _webView = nil;
    }
    if (_request) {
        _request = nil;
    }
    [self initializeWebViewWithScript];
    [self initializeButtons];
    
    [self refreshWebView];
    _label.text = @"新建(带script)成功!";
}

-(void) testAdd0
{
//    NSArray * heardCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:[NSDictionary
//    dictionaryWithObject:[[NSString alloc]
//    initWithFormat:@"cookiePasswd =%@", passString] //cookiePasswd也是后台给
//    forKey:@"Set-Cookie"]
//    forURL:[NSURL URLWithString:@"http://"]];
//     
//    [[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookies:heardCookie forURL:[NSURL URLWithString:@"http://"] mainDocumentURL:nil];

    //另一种设置Cookie的方法
    
   
    
    NSString* cookie = @"sid=95343a32-dccd-43cc-b4ec-71cbc95fe44b; Secure; HttpOnly; Expires=29-12-2023 16:40:19";
    NSArray *headeringCookie = [NSHTTPCookie
                                    cookiesWithResponseHeaderFields:
                                    @{
                                      @"Set-Cookie":cookie,
                                      }
                                    forURL:[NSURL URLWithString:@"http://27.128.162.66:58080/hbyqpt"]];
    // 通过setCookies方法，完成设置，这样只要一访问URL为HOST的网页时，会自动附带上设置好的header
     [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie forURL:[NSURL URLWithString:@"http://27.128.162.66:58080/hbyqpt"]
    mainDocumentURL:nil];
    
    {
//        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        for (NSHTTPCookie *cookie in headeringCookie) {
            
            NSLog(@"cookie-----%@", cookie);
            [cookieStore setCookie:cookie completionHandler:^{
                
            }];
        }
    }
    
    {
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        
        //get cookies

        [cookieStore getAllCookies:^(NSArray*_Nonnullcookies){
        NSLog(@"All cookies %@",_Nonnullcookies);
            for (NSHTTPCookie *cookie in _Nonnullcookies) {
                
                NSLog(@"cookie.name=%@,cookie.value=%@", cookie.name,cookie.value);
                [cookieStore deleteCookie:cookie completionHandler:^{
                    NSLog(@"delete cookie");
                    
                    
                }];
            }
        }];
        
        
    }
    
    
    NSLog(@"打印webView 0 cookie-----");
    {
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        
        //get cookies

        [cookieStore getAllCookies:^(NSArray*_Nonnullcookies){
        NSLog(@"All cookies %@",_Nonnullcookies);
            for (NSHTTPCookie *cookie in _Nonnullcookies) {
                
                NSLog(@"cookie.name=%@,cookie.value=%@", cookie.name,cookie.value);
            
            }
        }];
        
        
    }
    
    {
        //set cookie
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        NSMutableDictionary*dict=[NSMutableDictionary dictionary];

        dict[NSHTTPCookieName]=@"sid";

        dict[NSHTTPCookieValue]=@"95343a32-dccd-43cc-b4ec-71cbc95fe44b";

        dict[NSHTTPCookieDomain]=@"27.128.162.66";

        dict[NSHTTPCookiePath]=@"/hbyqpt";

        NSHTTPCookie*cookie=[NSHTTPCookie cookieWithProperties:dict];

        [cookieStore setCookie:cookie completionHandler:^{
        NSLog(@"set cookie");

        }];
    
    }
 
    NSLog(@"打印webView 1 cookie-----");
    {
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        
        //get cookies

        [cookieStore getAllCookies:^(NSArray*_Nonnullcookies){
        NSLog(@"All cookies %@",_Nonnullcookies);
            for (NSHTTPCookie *cookie in _Nonnullcookies) {
                
                NSLog(@"cookie.name=%@,cookie.value=%@", cookie.name,cookie.value);
            
            }
        }];
        
        
    }
    
}

-(void) testAdd
{

    {
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        
        //get cookies

        [cookieStore getAllCookies:^(NSArray*_Nonnullcookies){
        NSLog(@"del all cookies %@",_Nonnullcookies);
            for (NSHTTPCookie *cookie in _Nonnullcookies) {
                
                NSLog(@"delete cookie.name=%@,cookie.value=%@", cookie.name,cookie.value);
             
                [cookieStore deleteCookie:cookie completionHandler:^{
                    NSLog(@"delete cookie");
                    
                    
                }];
            }
        }];
        
        
    }
    
    NSLog(@"打印webView 00 cookie-----");
    {
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        
        //get cookies

        [cookieStore getAllCookies:^(NSArray*_Nonnullcookies){
        NSLog(@"All cookies %@",_Nonnullcookies);
            for (NSHTTPCookie *cookie in _Nonnullcookies) {
                
                NSLog(@"cookie.name=%@,cookie.value=%@", cookie.name,cookie.value);
            
            }
        }];
        
        
    }
    
//    
//    NSString* cookie = @"sid=95343a32-dccd-43cc-b4ec-71cbc95fe44b; Secure; HttpOnly; Expires=30-12-2023 16:40:19";
//    NSArray *headeringCookie = [NSHTTPCookie
//                                    cookiesWithResponseHeaderFields:
//                                    @{
//                                      @"Set-Cookie":cookie,
//                                      }
//                                    forURL:[NSURL URLWithString:@"http://27.128.162.66:58080/hbyqpt"]];
//    // 通过setCookies方法，完成设置，这样只要一访问URL为HOST的网页时，会自动附带上设置好的header
//     [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie forURL:[NSURL URLWithString:@"http://27.128.162.66:58080/hbyqpt"]
//    mainDocumentURL:nil];
//    
//    {
//        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
//        for (NSHTTPCookie *cookie in headeringCookie) {
//            
//            NSLog(@"cookie-----%@", cookie);
//            [cookieStore setCookie:cookie completionHandler:^{
//                
//            }];
//        }
//    }
//    
    
    
    
    
    
    {
        //set cookie
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        NSMutableDictionary*dict=[NSMutableDictionary dictionary];

        dict[NSHTTPCookieName]=@"sid";

        dict[NSHTTPCookieValue]=@"95343a32-dccd-43cc-b4ec-71cbc95fe44b";

        dict[NSHTTPCookieDomain]=@"27.128.162.66";

        dict[NSHTTPCookiePath]=@"/hbyqpt";

        NSHTTPCookie*cookie=[NSHTTPCookie cookieWithProperties:dict];

        [cookieStore setCookie:cookie completionHandler:^{
        NSLog(@"set cookie");

        }];
    
    }
 
    NSLog(@"打印webView 1 cookie-----");
    {
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        
        //get cookies

        [cookieStore getAllCookies:^(NSArray*_Nonnullcookies){
        NSLog(@"All cookies %@",_Nonnullcookies);
            for (NSHTTPCookie *cookie in _Nonnullcookies) {
                
                NSLog(@"cookie.name=%@,cookie.value=%@", cookie.name,cookie.value);
            
            }
        }];
        
        
    }
    
}

- (void)refreshWebView {
    if (!_request) {
        
//        [self testAdd];
        
        NSString *urlstr = @"http://27.128.162.66:58080/hbyqpt/view/app/realTimePicture.jsp?beginTime=2023-12-21&endTime=2023-12-28";
        //@"http://192.168.0.101/index.php"
        
        NSMutableURLRequest * Request_zsj = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10000];
            
//        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20];

        /*
         Host: 27.128.162.66:58080
         Connection: keep-alive
         Pragma: no-cache
         Cache-Control: no-cache
         Upgrade-Insecure-Requests: 1
         User-Agent: User-Agent
         X-Requested-With: com.ecc.hbyingjiban
         Accept-Encoding: gzip, deflate
         Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
         Cookie: sid=ecb592b7-4179-4824-bca7-f7888df63a29

         */
        [Request_zsj setValue:@"User-Agent" forHTTPHeaderField:@"User-Agent"];
        
        [Request_zsj setValue:@"no-cache" forHTTPHeaderField:@"Pragma"];
        [Request_zsj setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
        [Request_zsj setValue:@"com.ecc.hbyingjiban" forHTTPHeaderField:@"X-Requested-With"];
        //95343a32-dccd-43cc-b4ec-71cbc95fe44b
        [Request_zsj setValue:@"sid=95343a32-dccd-43cc-b4ec-71cbc95fe44b" forHTTPHeaderField:@"Cookie"];
        
        _webView.customUserAgent = @"User-Agent";
        
        self.request= Request_zsj;
    }
    [_webView loadRequest:_request];
    _label.text = @"刷新成功!";
}

- (void)deleteCookiesFiles {
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
    NSError *errors;
    [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    
    _label.text = @"清理磁盘成功!";
}

- (void)deleteCookiesStotage {
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    
    for (NSHTTPCookie *cookie in cookies) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
    _label.text = @"清理内存成功!";

}

- (void)initializeWebView {
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 200, 200, 200)];
    self.webView.backgroundColor = [UIColor yellowColor];
    self.webView.frame = self.view.bounds;
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self.view addSubview:_webView];
}

- (void)initializeWebViewWithScript {
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
    config.preferences = [WKPreferences new];
    config.preferences.minimumFontSize = 20.f;
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    WKUserContentController *userContentController = config.userContentController;
    //sid=95343a32-dccd-43cc-b4ec-71cbc95fe44b
    
//    NSString *cookieSource = [NSString stringWithFormat:@"document.cookie = 'JSESSIONID=95343a32-dccd-43cc-b4ec-71cbc95fe44b; Secure; HttpOnly; Expires=29-12-2023 16:05:03;'"];
    NSString *cookieSource = [NSString stringWithFormat:@"document.cookie = 'sid=%@;Secure; HttpOnly;'", @"95343a32-dccd-43cc-b4ec-71cbc95fe44b"];
    
    WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookieSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    
    
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 200, 200, 200) configuration:config];
    self.webView.backgroundColor = [UIColor yellowColor];
    self.webView.frame = self.view.bounds;
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self.view addSubview:_webView];
}

- (void)initializeButtons {
    UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(200, 20, 100, 30)];
    clearButton.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1];
    [clearButton setTitle:@"清理磁盘" forState:UIControlStateNormal];
    [clearButton addTarget:self action:@selector(deleteCookiesFiles) forControlEvents:UIControlEventTouchUpInside];
   // [_webView addSubview:clearButton];
    
    UIButton *clearButton2 = [[UIButton alloc] initWithFrame:CGRectMake(200, 60, 100, 30)];
    clearButton2.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1];
    [clearButton2 setTitle:@"清理内存" forState:UIControlStateNormal];
    [clearButton2 addTarget:self action:@selector(deleteCookiesStotage) forControlEvents:UIControlEventTouchUpInside];
  //  [_webView addSubview:clearButton2];
    
    UIButton *newButton = [[UIButton alloc] initWithFrame:CGRectMake(200, 100, 100, 30)];
    newButton.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1];
    [newButton setTitle:@"新建(普通)" forState:UIControlStateNormal];
    [newButton addTarget:self action:@selector(reCreateWebView) forControlEvents:UIControlEventTouchUpInside];
   // [_webView addSubview:newButton];
    
    
    UIButton *newButton2 = [[UIButton alloc] initWithFrame:CGRectMake(200, 140, 100, 30)];
    newButton2.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1];
    [newButton2 setTitle:@"新建(带script)" forState:UIControlStateNormal];
    [newButton2 addTarget:self action:@selector(reCreateWebViewWithScript) forControlEvents:UIControlEventTouchUpInside];
    [newButton2.titleLabel setFont:[UIFont systemFontOfSize:14]];
   // [_webView addSubview:newButton2];
    
    UIButton *refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(200, 580, 100, 30)];
    refreshButton.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1];
    [refreshButton setTitle:@"刷新" forState:UIControlStateNormal];
    [refreshButton addTarget:self action:@selector(refreshWebView) forControlEvents:UIControlEventTouchUpInside];
    [_webView addSubview:refreshButton];
    
    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 220, 200, 50)];
    _label.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    _label.textColor = [UIColor blackColor];
    _label.textAlignment = NSTextAlignmentCenter;
    
//    [_webView addSubview:_label];
}

- (void)becomeActive {
//    NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://10.129.19.55/index.php"]];
    NSHTTPCookieStorage *cookieJar2 = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in cookieJar2.cookies) {
        NSLog(@"becomeActive-----NSHTTPCookieStorage中的cookie%@", cookie);
    }
}

#pragma mark - WKNavigationDelegate
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"页面开始加载时调用。   2");
    
//    [self testAdd];
}

//解决 页面内跳转（a标签等）还是取不到cookie的问题
- (void)getCookie
{
    
    //取出cookie
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    //js函数
    NSString *JSFuncString =
    @"function setCookie(name,value,expires)\
    {\
    var oDate=new Date();\
    oDate.setDate(oDate.getDate()+expires);\
    document.cookie=name+'='+value+';expires='+oDate+';path=/'\
    }\
    function getCookie(name)\
    {\
    var arr = document.cookie.match(new RegExp('(^| )'+name+'=([^;]*)(;|$)'));\
    if(arr != null) return unescape(arr[2]); return null;\
    }\
    function delCookie(name)\
    {\
    var exp = new Date();\
    exp.setTime(exp.getTime() - 1);\
    var cval=getCookie(name);\
    if(cval!=null) document.cookie= name + '='+cval+';expires='+exp.toGMTString();\
    }";
    
    //拼凑js字符串
    NSMutableString *JSCookieString = JSFuncString.mutableCopy;
    for (NSHTTPCookie *cookie in cookieStorage.cookies) 
    {
        NSLog(@"cookie.name:%@ cookie.value:%@", cookie.name, cookie.value);
        
        if ([cookie.name isEqualToString:@"sid"])
        {
            NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 600);", cookie.name, @"95343a32-dccd-43cc-b4ec-71cbc95fe44b"];
            [JSCookieString appendString:excuteJSString];
        }
        else
        {
            NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 600);", cookie.name, cookie.value];
            [JSCookieString appendString:excuteJSString];
        }
        
    }
    
    NSLog(@"JSCookieString:%@",JSCookieString);
    
   /* NSMutableString *JSCookieString = JSFuncString.mutableCopy;
    
    NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 10);", @"sid", @"95343a32-dccd-43cc-b4ec-71cbc95fe44b"];
    [JSCookieString appendString:excuteJSString];
    */
    
    //执行js
    [_webView evaluateJavaScript:JSCookieString completionHandler:^(NSString *result, NSError * _Nullable error) {
        NSLog(@"设置网页中的cookie为：\n%@",[result componentsSeparatedByString:@"; "]);
    }];
    
}

//内容返回时调用，得到请求内容时调用(内容开始加载) -> view的过渡动画可在此方法中加载
//- (void)webView:(WKWebView *)webView didCommitNavigation:( WKNavigation *)navigation
//{
//    NSLog(@"内容返回时调用，得到请求内容时调用。 4");
//}
//页面加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:( WKNavigation *)navigation
{
    NSLog(@"页面加载完成时调用。 5");
    
//    [self getCookie];
    
//    [self testAdd];
    
}
//请求失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"error1:%@",error);
}
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"error2:%@",error);
}
//在请求发送之前，决定是否跳转 -> 该方法如果不实现，系统默认跳转。如果实现该方法，则需要设置允许跳转，不设置则报错。
//该方法执行在加载界面之前
//Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed to -[ViewController webView:decidePolicyForNavigationAction:decisionHandler:] was not called'
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    
    NSLog(@"在请求发送之前，决定是否跳转。  1");
    
    NSLog(@"decidePolicyForNavigationAction");
//    NSMutableURLRequest *mutableRequest = [navigationAction.request mutableCopy];
    NSDictionary *requestHeaders = navigationAction.request.allHTTPHeaderFields;
    
    NSString * cookieValue = [requestHeaders objectForKey:@"Cookie"];
    
    NSLog(@"webView.URL.absoluteString:%@",webView.URL.absoluteString);
    
    NSLog(@"cookieValue:%@",cookieValue);
    
    
    
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    
    //不允许跳转
    //    decisionHandler(WKNavigationActionPolicyCancel);
    NSLog(@"在请求发送之前，决定是否跳转。  1");
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    self.title = @"";
    [webView evaluateJavaScript:@"document.cookie" completionHandler:^(NSString *result, NSError * _Nullable error) {
        NSLog(@"网页中的cookie为：\n%@",[result componentsSeparatedByString:@"; "]);
    }];
}

//在收到响应后，决定是否跳转（同上）
//该方法执行在内容返回之前
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
    NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
    
    NSLog(@"decidePolicyForNavigationResponse");
    
    NSLog(@"response.URL.absoluteString:%@",response.URL.absoluteString);
    
    NSLog(@"[response allHeaderFields]:%@",[response allHeaderFields]);
    
    NSDictionary *responseHeaders = [response allHeaderFields];
    NSString *cookieHeader = [responseHeaders objectForKey:@"Set-Cookie"];
    NSLog(@"cookieHeader:%@",cookieHeader);
    
    
    // 方法一
//        NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
//        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
        NSLog(@"response-cookies = %@",cookies);
        
        //方法二
        NSString *cookieString = [[response allHeaderFields] valueForKey:@"Set-Cookie"];
        NSLog(@"cookieString = %@",cookieString);
        
        //方法三（如果有的话）
        NSArray<NSHTTPCookie *> *httpCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
        NSLog(@"httpCookies = %@",httpCookies);
        
        //方法四
        if(@available(iOS 11, *)){
            //WKHTTPCookieStore的使用
            WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
            {
                NSMutableDictionary*dict=[NSMutableDictionary dictionary];
                
                dict[NSHTTPCookieName]=@"sid";
                
                dict[NSHTTPCookieValue]=@"95343a32-dccd-43cc-b4ec-71cbc95fe44b";
                
                dict[NSHTTPCookieDomain]=@"27.128.162.66";
                
                dict[NSHTTPCookiePath]=@"/hbyqpt";
                
                NSHTTPCookie*cookie=[NSHTTPCookie cookieWithProperties:dict];
                
                [cookieStore setCookie:cookie completionHandler:^{
                    NSLog(@"set cookie");
                    
                }];
            }
            
            //获取 cookies
            [cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> * _Nonnull cookies) {
                [cookies enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSLog(@"cookieStore-cookies_%@:%@",@(idx),obj);
                }];
            }];
        }
        //将cookie设置到本地
        for (NSHTTPCookie *cookie in cookies) {
            //NSHTTPCookie cookie
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
        
        decisionHandler(WKNavigationResponsePolicyAllow);
    
  

    
//    NSString *cookieHeader = [responseHeaders objectForKey:@"Set-Cookie"];
//
//    NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//        NSArray *cookiestemp = [sharedHTTPCookieStorage cookiesForURL:response.URL];
//        NSEnumerator *enumerator = [cookiestemp objectEnumerator];
//        NSHTTPCookie *cookietemp;
//        while (cookietemp = [enumerator nextObject]) {
//            NSLog(@"COOKIE{name: %@, value: %@}", [cookietemp name], [cookietemp value]);
//            }
//    
//    //读取wkwebview中的cookie 方法1
//    for (NSHTTPCookie *cookie in cookiestemp) {
//        if (@available(iOS 11.0, *)) {
////            [_webView.configuration.websiteDataStore.httpCookieStore setCookie:cookie completionHandler:^{
////
////            }];
//            
//            WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
//            for (NSHTTPCookie *cookie in cookies) {
//                [cookieStore setCookie:cookie completionHandler:^{
//                    
//                }];
//            }
//            
//        } else {
//            // Fallback on earlier versions
//            NSMutableArray *mCookies = [NSMutableArray new];
//            for (NSHTTPCookie *cookie in cookies) {
//                [mCookies addObject:cookie];
//            }
//            NSDictionary *headerParams = [NSHTTPCookie requestHeaderFieldsWithCookies:mCookies];
//            ///设置请求头 -- 携带NSHTTPCookieStorage容器中cookie数据
////            request.allHTTPHeaderFields = headerParams;
//        }
//        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
//        NSLog(@"wkwebview中的cookie:%@", cookie);
//        s_cookie = cookie;
//    }
    
    //95343a32-dccd-43cc-b4ec-71cbc95fe44b
    
    //另一种设置Cookie的方法
//    NSString* cookie = @"sid=95343a32-dccd-43cc-b4ec-71cbc95fe44b;Expires=29-12-2024 10:47:40;path=/hbyqpt;Secure; HttpOnly;";
//    NSArray *headeringCookie = [NSHTTPCookie
//                                    cookiesWithResponseHeaderFields:
//                                    @{
//                                      @"Set-Cookie":cookie,
//                                      }
//                                    forURL:[NSURL URLWithString:@"http://27.128.162.66:58080/hbyqpt"]];
//    // 通过setCookies方法，完成设置，这样只要一访问URL为HOST的网页时，会自动附带上设置好的header
//     [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie forURL:[NSURL URLWithString:@"http://27.128.162.66:58080/hbyqpt"]
//    mainDocumentURL:nil];
    //
    
//    NSString* cookie = @"sid=95343a32-dccd-43cc-b4ec-71cbc95fe44b;Expires=29-12-2024 10:47:40;path=/hbyqpt;Secure; HttpOnly;";
//    NSArray *headeringCookie = [NSHTTPCookie
//                                    cookiesWithResponseHeaderFields:
//                                    @{
//                                      @"Set-Cookie":cookie,
//                                      }
//                                    forURL:[NSURL URLWithString:@"http://27.128.162.66:58080/hbyqpt"]];
//    // 通过setCookies方法，完成设置，这样只要一访问URL为HOST的网页时，会自动附带上设置好的header
//     [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie forURL:[NSURL URLWithString:@"http://27.128.162.66:58080/hbyqpt"]
//    mainDocumentURL:nil];
//    
    //读取wkwebview中的cookie 方法2 读取Set-Cookie字段
//    NSString *cookieString = [[response allHeaderFields] valueForKey:@"Set-Cookie"];
//    NSLog(@"wkwebview中的cookie:%@", cookieString);
    
    //看看存入到了NSHTTPCookieStorage了没有
//    NSHTTPCookieStorage *cookieJar2 = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    for (NSHTTPCookie *cookie in cookieJar2.cookies) {
//        NSLog(@"NSHTTPCookieStorage中的cookie%@", cookie);
//    }
    
//    decisionHandler(WKNavigationResponsePolicyAllow);
    
}

///WKWebView第一次发起URL请求时 将NSHTTPCookieStorage中cookie同步到WKWebView中
- (void)syncCookieToWKWithFirstRequest:(NSMutableURLRequest *)request {
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    if (@available(iOS 11.0, *)) {
        WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
        for (NSHTTPCookie *cookie in cookies) {
            [cookieStore setCookie:cookie completionHandler:^{
                
            }];
        }
    } else {
        NSMutableArray *mCookies = [NSMutableArray new];
        for (NSHTTPCookie *cookie in cookies) {
            [mCookies addObject:cookie];
        }
        NSDictionary *headerParams = [NSHTTPCookie requestHeaderFieldsWithCookies:mCookies];
        ///设置请求头 -- 携带NSHTTPCookieStorage容器中cookie数据
        request.allHTTPHeaderFields = headerParams;
    }
}

//接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"接收到服务器跳转请求之后调用");
}
-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
    NSLog(@"webViewWebContentProcessDidTerminate");
}

@end
